<template>
  <div>
    <el-dialog
      title="流程查看"
      :visible="visible"
      width="60%"
      @close="visible = false"
      :close-on-click-modal="false"
    >
      <span slot="title">
        <span>流程查看</span>
        &nbsp; &nbsp; &nbsp;
        <el-checkbox v-model="showOnlyAvailablePath" @change="showOnlyAvailablePathChange">仅展示有效路径</el-checkbox        >
      </span>
      <workflowEditPanel
        ref="workflowEditPanel"
        :nodeData="availableNodeData"
        :showStateTip="showStateTip"
      ></workflowEditPanel>

      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="confirm" size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import workflowEditPanel from "@/components/Workflow/panelView";

export default {
  components: { workflowEditPanel },
  props: {},
  watch: {
    value: {
      handler() {
        //this.load();
      },
      deep: true,
    },
    visible(newVal, oldVal) {
      if (!newVal && oldVal) this.hide();
    },
  },
  model: {
    prop: "value",
    event: "change",
  },
  data() {
    return {
      loading: false,
      visible: false,
      defaultLabelWidth: "150px",

      nodeData: {},
      data: {},
      showStateTip: false,
      forecastNodeUsers: [],
      showOnlyAvailablePath: false,
      showOnlyAvailableNodeData:{} ,
    };
  },
  computed: {
    availableNodeData() {
      return this.showOnlyAvailableNodeData && this.showOnlyAvailableNodeData.nodeList && this.showOnlyAvailableNodeData.nodeList.length > 0
        ? this.showOnlyAvailableNodeData
        : this.nodeData;
    },
  },
  methods: {
    confirm() {
      this.commit();
    },
    show(value) {
      
      // {version:'',id:''}
      this.visible = true;
      this.showOnlyAvailableNodeData = {}
      this.loadData(value.version, value.id, value.taskId);
    },
    hide() {
      this.visible = false;
      this.value = {};
      this.control = {};
    },
    loadData(value) {},
    commit() {
      this.hide();
    },
    loadData(versionno, id, workTaskId) {
      let _this = this;
      this.$store
        .dispatch("workflow/getWorkflowVersion", { versionno, id })
        .then((res) => {
          _this.nodeData =
            res.drawingInfo.length == 0
              ? this.defaultNode()
              : JSON.parse(res.drawingInfo);
          _this.data = res;
          if (_this.nodeData.nodeList)
            _this.nodeData.nodeList.forEach((n) => {
              n.viewOnly = true;
              n.state = "";
            });
          _this.$refs.workflowEditPanel.loadNodeData();

          if (workTaskId) {
            this.showStateTip = true;
            this.getAllTaskStepsOfWorkTask(workTaskId);
            this.getForecastNodeUsers4Task(workTaskId);
          }
        });
    },
    defaultNode() {
      return {
        name: "",
        nodeList: [],
        lineList: [],
      };
    },
    getAllTaskStepsOfWorkTask(taskid) {
      this.$store
        .dispatch("workflow/getAllTaskStepsOfWorkTask", {
          worktaskId: taskid,
        })
        .then((res) => {
          let nodeState = {};
          for (let i = res.length - 1; i >= 0; i--) {
            let step = res[i];
            //将步骤分组，并提取最新一组的成员 和状态，一组中有不同状态时，已待处理的为准
            if (typeof nodeState[step.nodeId] == "undefined") {
              nodeState[step.nodeId] = {
                isHandled: step.isHandled,
                handleUsers: [step],
              };
            } else {
              nodeState[step.nodeId].isHandled = step.isHandled;
              nodeState[step.nodeId].handleUsers.push(step);
            }
          }
          this.nodeData.nodeList.forEach((n) => {
            if (typeof nodeState[n.id] == "undefined") {
              n.state = "pending";
            } else {
              n.state = nodeState[n.id].isHandled ? "success" : "running";
              //提取数据展示当前节点审批人员（已审批和审批中，并且不是‘未处理’）
              n.handleUsersOfNode = (nodeState[n.id].handleUsers || [])
                .filter((step) => step.handleType !== 4)
                .map((step) => ({
                  userName: step.handleUser.name,
                  handleType: step.handleType,
                  handlerTime: this.dateFormat(step.handlerTime),
                  groupId: step.groupId,
                  userId: step.handleUser.id,
                }));
              n.handleUsersOfNode = this.filterLatestGroupHandleUsers(
                n.handleUsersOfNode
              );
            }
          });
          this.$refs.workflowEditPanel.loadNodeData();
        })
        .catch((e) => {
          this.loading = false;
        });
    },
    dateFormat(timeStr) {
      let dt = new Date(timeStr);
      // console.log("dt"+dt);
      if (dt.getFullYear() < 2000) {
        return "";
      }
      return (
        dt.getFullYear() +
        "-" +
        (dt.getMonth() + 1) +
        "-" +
        dt.getDate() +
        " " +
        dt.getHours() +
        ":" +
        dt.getMinutes()
      );
    },

    filterLatestGroupHandleUsers(handleUsers) {
      handleUsers = handleUsers || [];
      if (handleUsers.length < 2) return handleUsers;

      let first = handleUsers[handleUsers.length - 1];
      let userResult = [first];
      for (let index = handleUsers.length - 2; index > -1; index--) {
        let item = handleUsers[index];
        if (item.groupId !== first.groupId || item.userId === first.userId)
          break;
        userResult.push(item);
      }
      return userResult;
    },
    getForecastNodeUsers4Task(taskId) {
      this.$store
        .dispatch("workflow/getForecastNodeUsers4Task", { taskId })
        .then((res) => {
          this.forecastNodeUsers = res;
        });
    },
    showOnlyAvailablePathChange() {
      if (!this.showOnlyAvailablePath) {
        this.showOnlyAvailableNodeData = [];
      } else {
        let nodeIds = this.forecastNodeUsers.map((u) => u.nodeId);
        let result = { ...this.nodeData };
        result.nodeList = this.nodeData.nodeList.filter(
          (n) => nodeIds.indexOf(n.id) > -1
        );
        this.showOnlyAvailableNodeData = result;
      }
      if (this.$refs.workflowEditPanel)
        this.$refs.workflowEditPanel.loadNodeData();
    },
  },
};
</script>

<style></style>
